import 'dart:async';

import 'package:auto_route/auto_route.dart';
import 'package:distribution_mall_flutter/constant/cf_constant.dart';
import 'package:distribution_mall_flutter/constant/constant.dart';
import 'package:distribution_mall_flutter/constant/image_constant.dart';
import 'package:distribution_mall_flutter/constant/status_constant.dart';
import 'package:distribution_mall_flutter/entity/pay/pay.dart';
import 'package:distribution_mall_flutter/generated/l10n.dart';
import 'package:distribution_mall_flutter/mixins/page_stay_time.dart';
import 'package:distribution_mall_flutter/provider/common/pay_self.dart';
import 'package:distribution_mall_flutter/router/route_utils.dart';
import 'package:distribution_mall_flutter/utils/common_third.dart';
import 'package:distribution_mall_flutter/utils/common_widget.dart';
import 'package:distribution_mall_flutter/utils/image_loader.dart';
import 'package:distribution_mall_flutter/router/router.gr.dart';
import 'package:distribution_mall_flutter/widgets/loading.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:url_launcher/url_launcher.dart';

@RoutePage()
class PayLoadingPage extends ConsumerStatefulWidget {
  final String distributionOrderId;
  final String paymentType;
  final String receiptPaymentId;
  // 是否跳过free，cod，默认 false，只有在订单列表入口 才为 true。
  final bool skipCodFree;

  const PayLoadingPage(
      {super.key,
      @pathParam required this.receiptPaymentId,
      @pathParam required this.distributionOrderId,
      @pathParam required this.paymentType,
      this.skipCodFree = false});

  @override
  createState() {
    return _PayLoadingPage();
  }
}

class _PayLoadingPage extends ConsumerState<PayLoadingPage>
    with PageStayTime<PayLoadingPage> {
  Timer? _oneShotTimer;

  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((_) async {
      EPLoading.showLoadig();
      // 只要是 cod 或 freepay（0元） 就一定不能调用 getOrderPayment 接口 ！！！！！！！！！！！！！！！！！
      if ((widget.paymentType == PayType.cod ||
              widget.paymentType == PayType.free) &&
          !widget.skipCodFree) {
        if (widget.paymentType == PayType.free) {
          queryPaymentState(widget.receiptPaymentId);
        } else {
          if (widget.paymentType == PayType.cod) {
            Future.delayed(const Duration(seconds: 2), () {
              go2page();
            });
          }
        }
        return;
      }

      (await ref.read(paySelfProvider.notifier).getOrderPayment({
        'distributionOrderId': widget.distributionOrderId,
        'paymentType': widget.paymentType,
      }))
          .yes((data) async {
        EPLoading.dis();
        if (widget.paymentType == PayType.cod) {
          Future.delayed(const Duration(seconds: 2), () {
            go2page();
          });
          return;
        }

        String? url = data?.externalUrlParams?.receiptUrl;
        // 打开外部浏览器
        if (url != null && widget.paymentType != PayType.cod) {
          if (url.isNotEmpty) {
            if (await canLaunchUrl(Uri.parse(url))) {
              await launchUrl(Uri.parse(url),
                  mode: LaunchMode.externalApplication);
            } else {
              EPToast.showToast('Failed to open browser');
            }
          }
        }

        if (data != null && data.receiptPaymentId?.isNotEmpty == true) {
          if (_oneShotTimer != null) {
            _oneShotTimer?.cancel();
          }
          queryPaymentState(data.receiptPaymentId ?? '');
        }
      }).no((err) {
        go2page();
      });
    });
  }

  @override
  initPageStayTime();

  @override
  didPop() {
    _oneShotTimer?.cancel();
  }

  @override
  void dispose() {
    super.dispose();
    _oneShotTimer?.cancel();
  }

  go2page() {
    _oneShotTimer?.cancel();
    EPLoading.dis();
    appRouter.replace(
        OrderDetailRoute(distributionOrderId: widget.distributionOrderId));
  }

  // 获取支付状态
  queryPaymentState(String receiptPaymentId) {
    if (receiptPaymentId.isEmpty) return;
    // 轮询，直到订单状态已支付 或 服务问题 结束
    _oneShotTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      ref
          .read(paySelfProvider.notifier)
          .queryPaymentState(receiptPaymentId, widget.distributionOrderId)
          .then((data) {
        if (data == null) {
          EPLoading.dis();
          _oneShotTimer?.cancel();
          return;
        }
        if (OrderPayStatusEnum.getStatusIndex(data.paymentState) >
            OrderPayStatusEnum.toPay.index) {
          go2page();
        }
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    ref.watch(paySelfProvider);

    return Scaffold(
        appBar: AppBar(
          scrolledUnderElevation: 0,
          backgroundColor: Colors.white,
          leading: Padding(
            padding: const EdgeInsets.only(left: 16),
            child: CommonBtnWidget.arrowBack(),
          ),
        ),
        body: Container(
          margin: const EdgeInsets.only(top: EdgeConstant.edge20),
          padding: const EdgeInsets.symmetric(horizontal: EdgeConstant.edge20),
          child: Column(
            children: [
              ImageLoader.imageNet(ImageConstant.elephantpal,
                  fit: BoxFit.contain, width: 139, height: 44),
              DefaultTextStyle(
                  style: const TextStyle(
                      fontSize: 15,
                      fontWeight: FontWeight.bold,
                      color: Colors.white),
                  child: Container(
                    padding: const EdgeInsets.all(EdgeConstant.edge15),
                    margin: const EdgeInsets.only(top: 87),
                    decoration: const BoxDecoration(
                        color: ColorConstant.black89,
                        borderRadius: BorderRadius.all(Radius.circular(10))),
                    child: Column(
                      children: [
                        ...S.current.pay_loading_text
                            .split(',')
                            .map((item) => Text(
                                  item,
                                )),
                        GestureDetector(
                          onTap: () {
                            RouteUtils.back();
                          },
                          child: Text(
                            S.current.pay_loading_if,
                            style: const TextStyle(
                                decoration: TextDecoration.underline),
                          ),
                        )
                      ],
                    ),
                  )),
              const Expanded(
                  child: Center(
                child: Loading(),
              ))
            ],
          ),
        ));
  }
}
